<template>
  <div class="game-container">
    <!-- 背景图 -->
    <div class="background"></div>

    <!-- 词语显示框 -->
    <div class="word-display">
      <div class="word-content">
        <span class="word-text">{{ currentWord || '等待游戏开始...' }}</span>
        <span class="timer" v-if="timeLeft > 0">{{ timeLeft }}s</span>
      </div>
    </div>

    <!-- Canvas 绘画区域 -->
    <div class="canvas-wrapper">
      <canvas 
        ref="gameCanvas" 
        class="game-canvas"
        @mousedown="startDrawing"
        @mousemove="draw"
        @mouseup="stopDrawing"
        @mouseleave="stopDrawing"
        @touchstart="handleTouchStart"
        @touchmove="handleTouchMove"
        @touchend="handleTouchEnd"
      ></canvas>
      <div class="canvas-controls">
        <button class="tool-btn" @click="clearCanvas">清空画布</button>
        <div class="color-picker">
          <button 
            v-for="color in colors" 
            :key="color"
            class="color-btn"
            :style="{ backgroundColor: color }"
            @click="selectColor(color)"
            :class="{ active: selectedColor === color }"
          ></button>
        </div>
      </div>
    </div>

    <!-- 聊天窗口和输入区域容器 -->
    <div class="chat-container">
      <!-- 聊天窗口 -->
      <div class="chat-window">
        <div class="chat-messages">
          <div 
            v-for="(message, index) in chatMessages" 
            :key="index"
            class="message-item"
            :class="{ 'system-message': message.type === 'system', 'user-message': message.type === 'user' }"
          >
            <span v-if="message.type === 'user'" class="username">{{ message.nickedname }}:</span>
            <span class="message-content">{{ message.message }}</span>
          </div>
        </div>
      </div>

      <!-- 输入区域 -->
      <div class="input-area">
        <input 
          type="text" 
          v-model="messageInput" 
          placeholder="输入消息..." 
          class="message-input"
          @keyup.enter="sendMessage"
        />
        <button 
          class="send-btn" 
          @click="sendMessage"
        >
          发送
        </button>
      </div>
    </div>

    <!-- 底部按钮区域 -->
    <div class="bottom-buttons">
      <button 
        class="ready-btn" 
        @click="toggleReady"
        :class="{ ready: isReady }"
      >
        {{ isReady? '取消准备' : '准备' }}
      </button>
      <button class="player-list-btn" @click="showPlayerModal = true">
        玩家列表 ({{ players.length }})
      </button>
      <button class="leave-btn" @click="leaveGame">离开</button>
    </div>

    <!-- 玩家列表弹窗 -->
    <div class="modal" v-if="showPlayerModal">
      <div class="modal-content player-modal">
        <div class="modal-header">
          <h3>房间玩家列表</h3>
          <button class="close-btn" @click="showPlayerModal = false">×</button>
        </div>
        <div class="player-list-content">
          <div 
            v-for="player in players" 
            class="player-card"
            :class="{ 'is-current': player.isReady == 1, 'is-drawing': player.drawingstatus == 1 }"
          >
            <div class="avatar-wrapper">
              <img :src="config.api + 'data/get-picture?id=' + player.headpicture 
                || config.api + 'data/get-picture?id=0'" :alt="player.nickedname" class="player-avatar" />
            </div>
            <div class="player-info">
              <div class="player-name">{{ player.nickedname }}</div>
              <div class="player-status">
                <span v-if="player.drawingstatus == 1" class="status-tag drawing">绘画中</span>
                <span v-else-if="player.isready" class="status-tag ready">已准备</span>
                <span v-else class="status-tag waiting">等待中</span>
                <span  class="status-tag ready">得分: {{ player.grade }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount, nextTick, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import config from "@/config"
import axios from "axios"
import {onEvent, offEvent, initEventBus} from "@/utils/eventBus"

const router = useRouter()

verify()

// Canvas 相关
const gameCanvas = ref(null)
const isDrawing = ref(false)
const selectedColor = ref('#000000')
const colors = ['#000000', '#ff0000', '#00ff00', '#0000ff', '#ffff00', '#ff00ff', '#00ffff', '#ffffff']

// 游戏状态
const currentWord = ref('')
const timeLeft = ref(0)
const targettime = ref(0)
const isReady = ref(false)
const isGameStarted = ref(false)
const messageInput = ref('')
const drawingRight = ref(false)
let roomid = ref()
let timerid = null

// 玩家相关
const showPlayerModal = ref(false)
const players = reactive([
])
const current_user = ref()

// 聊天消息
const chatMessages = ref([
])

//界面初始化执行部分



// 获取鼠标/触摸位置
const getEventPosition = (e) => {
  const canvas = gameCanvas.value
  const rect = canvas.getBoundingClientRect()
  
  let clientX, clientY
  
  if (e.touches && e.touches.length > 0) {
    // 触摸事件
    clientX = e.touches[0].clientX
    clientY = e.touches[0].clientY
  } else {
    // 鼠标事件
    clientX = e.clientX
    clientY = e.clientY
  }
  
  return {
    x: clientX - rect.left,
    y: clientY - rect.top
  }
}

// Canvas 绘制函数
const startDrawing = (e) => {
  if (!drawingRight.value) return
  
  isDrawing.value = true
  const canvas = gameCanvas.value
  const ctx = canvas.getContext('2d')
  const pos = getEventPosition(e)
  
  ctx.beginPath()
  ctx.moveTo(pos.x, pos.y)
}

const draw = (e) => {
  if (!isDrawing.value || !isGameStarted.value) return
  
  e.preventDefault() // 防止页面滚动
  
  const canvas = gameCanvas.value
  const ctx = canvas.getContext('2d')
  const pos = getEventPosition(e)
  
  ctx.lineWidth = 3
  ctx.lineCap = 'round'
  ctx.strokeStyle = selectedColor.value
  
  ctx.lineTo(pos.x, pos.y)
  ctx.stroke()
  ctx.beginPath()
  ctx.moveTo(pos.x, pos.y)
}

const stopDrawing = async () => {
  isDrawing.value = false
  const ctx = gameCanvas.value.getContext('2d')
  ctx.beginPath()

  if (drawingRight.value) {
    let bd = gameCanvas.value.toDataURL('image/jpg')
    await axios.post(config.api + 'data/running-game', {
      boarddata: bd
    }, {
      withCredentials:true
    })
  }
}

// 触摸事件处理
const handleTouchStart = (e) => {
  startDrawing(e)
}

const handleTouchMove = (e) => {
  draw(e)
}

const handleTouchEnd = async () => {
  stopDrawing()
  if (drawingRight.value) {
    let bd = gameCanvas.value.toDataURL('image/jpg')
    await axios.post(config.api + 'data/running-game', {
      boarddata: bd
    }, {
      withCredentials:true
    })
  }
}

const clearCanvas = async () => {
  if (drawingRight.value == false) return 
  const canvas = gameCanvas.value
  const ctx = canvas.getContext('2d')
  ctx.clearRect(0, 0, canvas.width, canvas.height)
  if (drawingRight.value) {
    let bd = gameCanvas.value.toDataURL('image/jpg')
    await axios.post(config.api + 'data/running-game', {
      boarddata: null
    }, {
      withCredentials:true
    })
  }

}

const selectColor = (color) => {
  selectedColor.value = color
}

// 游戏逻辑函数
const sendMessage = async () => {
  if (!messageInput.value.trim()) return

  let response = await axios.post(config.api + "data/running-game", {
    message: {
      message: messageInput.value
    }
  }, {
    withCredentials: true
  })
  
  messageInput.value = ''
}

const toggleReady = async () => {
  let response = await axios.post(config.api + "data/running-game", {
    ready:{}
  }, {
    withCredentials: true
  })
  if (response.data.status != '0') {
    alert(response.data.msg)
    return
  }
}

const leaveGame = async () => {
  if (confirm('确定要离开游戏吗？')) {
    let response = await axios.post(config.api + "data/leave-room", { }, {
      withCredentials:true
    })
    if (response.data.status != "0") {
      alert(response.data.msg)
    }
    router.push('/')
  }
}


// 初始化 Canvas
const initCanvas = () => {
  const canvas = gameCanvas.value
  if (canvas) {
    canvas.width = canvas.offsetWidth
    canvas.height = canvas.offsetHeight - 50 // 减去控制按钮区域的高度
    
    const ctx = canvas.getContext('2d')
    ctx.fillStyle = '#ffffff'
    ctx.fillRect(0, 0, canvas.width, canvas.height)
  }
}

// 窗口大小改变时重置 Canvas
const handleResize = () => {
  //initCanvas()
}


const tongbu = async (data) => {
  //请求房间数据同步一下状态
  let response = await axios.post(config.api + "data/running-game", {}, {
    withCredentials: true
  })
  if (response.data.status == '-2') {
    router.replace('/')
  }
  else if (response.data.status != '0') {
    alert(response.data.msg)
    return
  }

  current_user.value = response.data.all_info.current_user //当前用户信息
  isReady.value = current_user.value.isready //准备状态同步 
  roomid.value = response.data.all_info.id //当前房间id
  
  isGameStarted.value = response.data.all_info.gamestatus //游戏开始状态
  //绘画权限
  drawingRight.value = response.data.all_info.current_user.drawingstatus == 1? true : false
  if (isGameStarted.value) {
    if (!drawingRight.value) {
      currentWord.value = response.data.all_info.hoster + "正在绘画中"
    }
    else {
      currentWord.value = response.data.all_info.currentword
    }
  }
  else {
    currentWord.value = null
  }
  targettime.value = response.data.all_info.targettime
  // 聊天信息
  chatMessages.value = []
  for (let i = 0; i < response.data.all_info.message_list.length; ++i) {
    let msg = response.data.all_info.message_list[i]
    chatMessages.value.push({
      type: msg['username'] == 'admin' ? 'system' : 'user',
      nickedname: msg['nickedname'],
      message: msg['message']
    })
  }

  //设置计时器
  if (isGameStarted.value && !timerid) {
    const timerfunction = () => {
      timeLeft.value = targettime.value - Math.floor(Date.now() / 1000)
      if (timeLeft.value > 0) {
        timerid = setTimeout(timerfunction, 1000);
      }
      else {
        timerid = null
        tongbu()
      }
    }
    timerfunction()
  }


  //用户列表同步下
  players.length = 0
  players.push(...response.data.all_info.userlist)
  const pen = gameCanvas.value.getContext('2d')
  //画板的操作
  if (drawingRight.value == false && response.data.all_info.boarddata) {
    
    let img = new Image()
    img.src = response.data.all_info.boarddata
    pen.drawImage(img, 0, 0)
  }
  else if (drawingRight.value == false) {
    pen.clearRect(0, 0, gameCanvas.value.width, gameCanvas.value.height)
  }
}

onMounted(async () => {
  initCanvas()
  initEventBus()
  window.addEventListener('resize', handleResize)

  await tongbu()
  onEvent("tongbu-" + roomid.value, tongbu)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize)
})

onUnmounted(() => {
  offEvent("tongbu-" + roomid.value, tongbu)
})


//一进到该界面先验证一下登录情况，验证不通过提示请登录然后返回登录界面
async function verify() {
    let response = await axios.post(config.api + 'auth/verify', { }, {
        withCredentials: true
    });
    if (response.data.status == "-1") {
        alert("您还没有登录");
        router.push("/login");  
    }
}



</script>

<style scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.game-container {
  position: relative;
  width: 100vw;
  height: 100vh;
  display: flex;
  flex-direction: column;
  gap: 10px;
  padding: 10px;
  font-family: 'Arial', sans-serif;
  overflow: hidden;
  touch-action: none; /* 禁用默认触摸行为 */
}

/* 背景图 */
.background {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image: url("@/pic/fengmian4.png");
  background-size: cover;
  background-position: center;
  z-index: -1;
  opacity: 0.8;
}

/* 词语显示框 */
.word-display {
  background-color: rgba(255, 255, 255, 0.95);
  border-radius: 12px;
  padding: 10px;
  text-align: center;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  margin-bottom: 5px;
  height: 50px;
  flex-shrink: 0;
}

.word-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.word-text {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.timer {
  font-size: 20px;
  font-weight: bold;
  color: #ff4444;
}

/* Canvas 区域 */
.canvas-wrapper {
  background-color: rgba(255, 255, 255, 0.95);
  border-radius: 12px;
  padding: 15px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  gap: 10px;
  flex: 1;
  min-height: 400px;
}

.game-canvas {
  width: 100%;
  flex: 1;
  background-color: white;
  border: 2px solid #ddd;
  border-radius: 8px;
  cursor: crosshair;
  touch-action: none; /* 禁用默认触摸行为 */
}

.canvas-controls {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-shrink: 0;
}

.tool-btn {
  padding: 8px 16px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

.tool-btn:hover {
  background-color: #0056b3;
}

.color-picker {
  display: flex;
  gap: 5px;
}

.color-btn {
  width: 25px;
  height: 25px;
  border: 2px solid #ddd;
  border-radius: 50%;
  cursor: pointer;
  transition: transform 0.2s;
}

.color-btn:hover,
.color-btn.active {
  transform: scale(1.2);
  border-color: #333;
}

/* 聊天容器 */
.chat-container {
  display: flex;
  flex-direction: column;
  background-color: rgba(255, 255, 255, 0.95);
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  height: 150px;
  flex-shrink: 0;
}

/* 聊天窗口 */
.chat-window {
  flex: 1;
  min-height: 0;
  height: 200px;
}

/* 聊天消息容器 */
.chat-messages {
  height: 100%;
  max-height: 170px;           /* 增加一点高度 */
  overflow-y: auto;
  padding: 10px;
  background-color: white;     /* 改成纯白，更清晰 */
  border-radius: 8px;
  border: 1px solid #ddd;      /* 加边框，便于调试 */
  font-size: 14px;             /* 确保字体够大 */
  color: #000;                 /* 明确文字颜色 */
  margin: 10px;
}

.message-item {
  margin-bottom: 6px;
  font-size: 13px;
  word-wrap: break-word;
}

.system-message {
  color: #6c757d;
  font-style: italic;
  text-align: center;
}

.user-message {
  color: #333;
}

.username {
  font-weight: bold;
  color: #007bff;
  margin-right: 5px;
}

/* 输入区域 */
.input-area {
  display: flex;
  gap: 10px;
  padding: 0 10px 10px;
  flex-shrink: 0;
}

.message-input {
  flex: 1;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 13px;
  outline: none;
}

.message-input:focus {
  border-color: #007bff;
}

.message-input:disabled {
  background-color: #f5f5f5;
}

.send-btn {
  padding: 10px 16px;
  background-color: #28a745;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 13px;
  cursor: pointer;
  transition: background-color 0.3s;
  white-space: nowrap;
}

.send-btn:hover:not(:disabled) {
  background-color: #218838;
}

.send-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

/* 底部按钮区域 */
.bottom-buttons {
  display: flex;
  gap: 10px;
  padding: 10px;
  background-color: rgba(255, 255, 255, 0.95);
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  flex-shrink: 0;
}

.ready-btn,
.player-list-btn,
.leave-btn {
  flex: 1;
  padding: 12px 20px;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.3s;
  white-space: nowrap;
}

.ready-btn {
  background-color: #ffc107;
  color: #212529;
}

.ready-btn:hover {
  background-color: #e0a800;
}

.ready-btn.ready {
  background-color: #28a745;
  color: white;
}

.player-list-btn {
  background-color: #17a2b8;
  color: white;
}

.player-list-btn:hover {
  background-color: #138496;
}

.leave-btn {
  background-color: #dc3545;
  color: white;
}

.leave-btn:hover {
  background-color: #c82333;
}

/* 弹窗样式 */
.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 6px 30px rgba(0, 0, 0, 0.2);
  max-width: 90%;
  max-height: 90%;
  overflow: hidden;
}

/* 玩家列表弹窗 */
.player-modal {
  width: 90%;
  max-width: 500px;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #eee;
}

.modal-header h3 {
  margin: 0;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #999;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-btn:hover {
  color: #333;
}

.player-list-content {
  padding: 20px;
  max-height: 400px;
  overflow-y: auto;
}

.player-card {
  display: flex;
  align-items: center;
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 10px;
  background-color: #f8f9fa;
  border: 1px solid #dee2e6;
  transition: all 0.3s;
}

.player-card:last-child {
  margin-bottom: 0;
}

.player-card.is-current {
  border-color: #007bff;
  background-color: #e3f2fd;
}

.player-card.is-drawing {
  border-color: #28a745;
  background-color: #d4edda;
}

.avatar-wrapper {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  overflow: hidden;
  margin-right: 15px;
  border: 2px solid #ddd;
}

.player-avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.player-info {
  flex: 1;
}

.player-name {
  font-weight: bold;
  font-size: 16px;
  color: #333;
  margin-bottom: 5px;
}

.status-tag {
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.status-tag.drawing {
  background-color: #d4edda;
  color: #155724;
}

.status-tag.ready {
  background-color: #d1ecf1;
  color: #0c5460;
}

.status-tag.waiting {
  background-color: #f8d7da;
  color: #721c24;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .game-container {
    padding: 5px;
  }
  
  .canvas-wrapper {
    min-height: 300px;
  }
  
  .chat-container {
    height: 120px;
  }
  
  .chat-messages {
    max-height: 80px;
  }
  
  .player-modal {
    width: 95%;
  }
  
  .player-list-content {
    max-height: 300px;
  }
}

@media (max-width: 480px) {
  .game-container {
    gap: 5px;
    padding: 5px;
  }
  
  .canvas-wrapper {
    min-height: 250px;
    padding: 10px;
  }
  
  .chat-container {
    height: 100px;
  }
  
  .chat-messages {
    max-height: 60px;
    padding: 8px;
    margin: 8px;
  }
  
  .message-item {
    font-size: 12px;
    margin-bottom: 4px;
  }
  
  .message-input {
    padding: 8px;
    font-size: 12px;
  }
  
  .send-btn {
    padding: 8px 12px;
    font-size: 12px;
  }
  
  .ready-btn,
  .player-list-btn,
  .leave-btn {
    padding: 10px 12px;
    font-size: 12px;
  }
  
  .modal-header {
    padding: 15px;
  }
  
  .player-list-content {
    padding: 15px;
  }
  
  .player-card {
    padding: 12px;
  }
  
  .avatar-wrapper {
    width: 40px;
    height: 40px;
  }
  
  .player-name {
    font-size: 14px;
  }
}
</style>